//部门管理

/**
 * 添加/编辑视图模型
 */
interface IDepartmentManagentDetailViewModel {
    /**
     * 标识符
     */
    id?: string;
    /**
     * 部门名称
     */
    name: string;
    /**
     * 权限值
     */
    roles: {role:string[]};
    /**
     * 专员类型
     */
    types: {type:string[]};
    /**
     * 保存事件
     */
    click: () => void;
  
}

/**
 * 视图模型
 */
interface IDepartmentManagentViewModel extends IBaseViewModel<IDepartmentManagentQueryTerms> {
    /**
     * ui-grid控制
     */
    gridOptions: uiGrid.IGridOptionsOf<DepartmentListItemResponse>;
    /**
     * 列表高度
     */
    heightA:number;
    /**
     * 添加/编辑视图
     */
    detail: IDepartmentManagentDetailViewModel;
    /**
     * 添加部门
     */
    addDepartment: () => void;
    /**
     * 编辑部门
     */
    editDepartment: (id: string) => void;
    /**
     * 删除部门
     */
    deleteDepartment: (id: string) => void;

    typeArr: {type:string[]};

    //权限列表
    authTree:ListResponse<visualAuthorizationListItemReponse>
    
    /**
    * 折叠h或者展开树
    */
    toggleTree:()=>void
    /**
    * 树的展开状态
    */
    treeExpand:boolean;
        
    authNumbers:{high:number[],middle:number[],low:number[]}
    secAuthTypeTag:string[]

    saveChecked:number;

    saveCheckedAuth:()=>void;
    /**
     * 编辑部门权限
     */
    editDepartAuthorization:(any)=>void;
    /**
     * 选中部门的名称
     */
    departmentName:string;
}

/**
 * 查询条件
 */
interface IDepartmentManagentQueryTerms {
    /**
     * 部门名称
     */
    name: string;
}

class DepartmentManagentController extends ListController<IDepartmentManagentViewModel, IDepartmentManagentQueryTerms> {
    gridApi: uiGrid.IGridApiOf<DepartmentListItemResponse>;
    selectedRow:any;
    
    constructor($scope: IDepartmentManagentViewModel,private $timeout:ng.ITimeoutService, private departmentService: IDepartmentService, 
        private $ngBootbox: BootboxService,private valueService:IValueService,private visualAuthorizationService:visualAuthorizationService,
        private $state:angular.ui.IStateService,private $location:ng.ILocationService) {
        super($scope);
        this.init();
    }

    init(): void {
        super.init();
        this.$scope.addDepartment = this.showAddDepartmentDialog;
        this.$scope.editDepartment = this.showEditDepartmentDialog;
        this.$scope.deleteDepartment = this.showDeleteDepartmentDialog;
        this.$scope.editDepartAuthorization=this.editDepartAuthorization;
        this.$scope.queryTerms = {
            name: "",
        };
        this.$scope.toggleTree=()=>{
            this.$scope.treeExpand=!this.$scope.treeExpand
        }
        this.$scope.gridOptions = {
            enableSorting: false,
            useExternalPagination: true,
            useExternalSorting: true,
            enableColumnResizing: true,
            paginationPageSizes: [10, 20, 30],
            columnDefs: [
                { name: "序号", field: "index", enableColumnMenu: false },
                { name: "部门名称", field: "name", enableColumnMenu: false },
                { name: "专员类型", field: "types", enableColumnMenu: false },
                { name: "员工数", field: "userCount", enableColumnMenu: false },
                {
                    name: "操作",
                    cellFilter: "checkmark",
                    cellTemplate: `<a data-toggle="modal" data-target="#myModal" class="fa fa-edit m-l-xs primary text-info" title="部门编辑" ng-click="grid.appScope.editDepartment(row.entity.id)"></a>
                                    <a data-toggle="modal" data-target="#authModal" class="fa fa-pencil-square m-l-xs primary text-info" title="权限编辑" ng-click="grid.appScope.editDepartAuthorization(row.entity)"></a>  
                                    <a class="primary fa fa-trash-o text-danger m-l-xs" title="删除" ng-click="grid.appScope.deleteDepartment(row.entity.id)"></a>`,
                    enableColumnMenu: false
                }
            ],
            onRegisterApi: (gridApi) => {
                this.gridApi = gridApi;
                gridApi.pagination.on.paginationChanged(this.$scope,(skipSize,pageSize)=>{
                    this.paginationChanged(skipSize,pageSize,this.$state);
                });
                // gridApi.pagination.on.paginationChanged(this.$scope, this.paginationChanged);
            }
        };
        
        this.query();
        this.$scope.authNumbers={
            high:[],
            middle:[],
            low:[]
        }
      
        this.$scope.secAuthTypeTag=[];
        this.$scope.departmentName = '';
        // this.visualAuthorizationService.getList().then(res=>{
        //     this.$scope.authTree=res.data
            
        // })
        this.$scope.saveChecked=0
        this.$scope.saveCheckedAuth=this.saveCheckedAuth;


    }

    loadData(queryTerms: IDepartmentManagentQueryTerms, skip: number, count: number): void {
        this.departmentService.getList(queryTerms.name, skip, count).then(result => {
            if (skip == 0) {
                this.$scope.gridOptions.paginationCurrentPage = 1;
            }

            this.$scope.gridOptions.totalItems = result.data.total;
            result.data.data.map((item, index) => item.index = skip++ +1);
            this.$scope.gridOptions.data = result.data.data;
            this.$scope.heightA = (this.$scope.gridOptions.data.length*39)+80;

            this.$scope.querying = false;
        }, error => {
            this.$scope.querying = false;
        });

    }

    localHistory():void{
        super.localHistory(this.$state)
    }
    getHistory():void{
        super.getHistory(this.$state,this.$location)
    }

    /**
     * 显示添加部门窗口
     */
    showAddDepartmentDialog = () => {
        $("#AuthorizationChecked").find("input[type='checkbox']").prop("checked", false);
        this.$scope.title = "添加部门";
        this.$scope.detail = {
            name: "",
            roles: {role:[]},
            types: {type:[]},
            click: this.addDepartment
        };

       this.$scope.detail.name="";
       this.$scope.detail.click = this.addDepartment;
    }

    addDepartment = () => {
        // if (!$("#departForm").valid()) { return };
        this.$ngBootbox.confirm("确定保存该数据吗？").then(e => {
            this.departmentService.add(
                this.$scope.detail.name,
                this.$scope.detail.roles.role,
                this.$scope.detail.types.type
            ).then(result => {
                this.reload();
                $('#myModal').modal('hide');
            })
        });
    }

    /**
     * 显示编辑部门窗口
     */
    showEditDepartmentDialog = (id: string) => {
        // this.
        $("#authorizationRepeat").find("input[name='itemCheckN']").prop("checked", false);
        this.$scope.title = "编辑部门";
        // var validator = $('#departForm').validate();
        // validator.form();
        // validator.hideErrors();
        $(".error").removeClass("error");

        this.departmentService.getDetail(id).then(result => {
            this.$scope.detail = {
                id: id,
                name: result.data.name,
                roles: {role:result.data.roles},
                types: {type:result.data.types},
                click: this.editDepartment
            };
        });
    }

    editDepartment = () => {
        this.$ngBootbox.confirm("确定保存该数据吗？").then(e => {
            this.departmentService.edit(
                this.$scope.detail.id,
                this.$scope.detail.name,
                this.$scope.detail.roles.role,
                this.$scope.detail.types.type
            ).then(result => {
                this.reload(this.$scope.gridOptions.paginationCurrentPage);
                // this.reload();
                $('#myModal').modal('hide');
            });
        });
    }

    showDeleteDepartmentDialog = (id: string) => {
        this.$ngBootbox.confirm("是否删除该部门？").then(e => {
            this.departmentService.delete(id).then(result => {
                this.reload(this.$scope.gridOptions.paginationCurrentPage);
                // this.reload();
            });
        });
    }
     /**
     * 编辑部门权限
     */
    editDepartAuthorization=(row)=>{
        this.$scope.departmentName = row.name;
        // console.log(row);
        this.visualAuthorizationService.getList(null,row.id).then(res=>{
            this.$scope.authTree=res.data
        })
        this.$scope.treeExpand=false;
        this.selectedRow=row;
    }

    saveCheckedAuth=()=>{
        // this.$scope.saveChecked++;
        
        this.$ngBootbox.confirm('确认保存数据吗').then(e=>{
            console.log(e)
            // console.log(this.$scope.authNumbers,this.$scope.secAuthTypeTag);
            let checkedNumbers={high:[],middle:[],low:[]},secAuthTags=[];
            
            let nodes=this.$scope.authTree.data;
            nodes&&nodes.forEach(firstAuth=>{
                firstAuth.secAuthTypeList&&firstAuth.secAuthTypeList.forEach(secNode=>{
                    secNode.visualAuthList&&secNode.visualAuthList.forEach(thNode=>{
                        if(thNode.isShow){
                            // checkedNumbers.push(thNode.authNumber);
                            let key=['high','middle','low'][thNode.level-1]  ;
                            if(key){

                                // console.log(checkedNumbers);
                                checkedNumbers[key].push(thNode.number);
                            }
                            
                            if(secAuthTags.indexOf(thNode.secAuthorizationTypeTag)===-1){
                                secAuthTags.push(thNode.secAuthorizationTypeTag);
                            }
                        }
                    })
                })
                
            })
            this.$scope.authNumbers=checkedNumbers;
            this.$scope.secAuthTypeTag=secAuthTags;
            let authObj={
                HighAuthNumber:this.$scope.authNumbers.high,
                //中等级权限
                MiddleAuthNumber:this.$scope.authNumbers.middle,
                //低等级权限
                LowAuthNumber:this.$scope.authNumbers.low,
                //二级权限标签
                SecAuthTypeTag:this.$scope.secAuthTypeTag
            }
            this.departmentService.editAuth(this.selectedRow.id,authObj).then(res=>{
                // console.log(res)
                this.reload(this.$scope.gridOptions.paginationCurrentPage);
                $('#authModal').modal('hide');
                
            })

        })
       

    }
}

angular.module('tms').controller('departmentManagentController', ['$scope','$timeout', 'departmentService', '$ngBootbox','valueService','visualAuthorizationService','$state','$location', DepartmentManagentController]);